package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    public void add(ArrayList<OrderSetting> list) {

        //判断集合是否为空
        if (list != null && list.size() > 0) {
            for (OrderSetting orderSetting : list) {
                long countByOrderDate = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
                //判断是否当前日期是否已经有预约设置
                if (countByOrderDate > 0) {
                    //已经有预约设置,执行更新操作
                    orderSettingDao.editNumberByOrderDate(orderSetting);
                } else {
                    //没有预约设置,执行插入操作
                    orderSettingDao.add(orderSetting);
                }
            }
        }
    }

    @Override
    public List<Map> getOrderSettingByMonth(String date) {
        String begin = date + "-1";
        String end = date + "-31";
        //用map封装数据
        Map<String, String> map = new HashMap<>();
        map.put("begin", begin);
        map.put("end", end);
        //调用dao,查询数据
        List<OrderSetting> list = orderSettingDao.getOrderSettingByMonth(map);
        List<Map> resultList = new ArrayList<>();
        //重新封装数据
        if (list != null & list.size() > 0){
            for (OrderSetting orderSetting : list) {
                Map<String,Object> m = new HashMap<>();
                m.put("date",orderSetting.getOrderDate().getDate());    //只需要获取日期的day
                m.put("number",orderSetting.getNumber());
                m.put("reservations",orderSetting.getReservations());
                resultList.add(m);
            }
        }
        return resultList;
    }

    @Override
    public void editOrderSettingByDate(OrderSetting orderSetting) {
        //根据日期查询是否已经进行过预约设置
        Date orderDate = orderSetting.getOrderDate();
        long countByOrderDate = orderSettingDao.findCountByOrderDate(orderDate);
        if (countByOrderDate > 0){
            //已经进行预约设置,执行更新操作
            orderSettingDao.editNumberByOrderDate(orderSetting);
        }else{
            //没有进行预约设置,执行插入
            orderSettingDao.add(orderSetting);
        }

    }
}
